from widgets.widget_base import Template

import blockarticle.widget_manager as widget_manager
WidgetManager = widget_manager.WidgetManager()
WidgetManager.LoadWidgets()

class ArticleView:
    """View of article, for displaing article"""   
    
    InsertForm = """<span xmlns:py="http://purl.org/kid/ns#" py:strip="True">
        <select id="select${ID}">
            <span py:strip="True" py:for="Module in ModuleList" value="${Module}">
                <option value="*">[${Module}]</option>
                <option py:for="Widget in ModuleList[Module].WidgetList" value="${Module}.${Widget}">${Widget}</option>
            </span>
        </select>
        <a href="javascript: LoadCommandResult('insert', {'id': '${ID}', 'push_back': '${PushBack}', 'type': document.getElementById('select${ID}').value});">Insert</a>
    </span>
    """
    
    def __init__(self, ID):
        import model
        
        self.Article = model.Article.get(ID)
    
    def Render(self, DisplayEditable = False):
        """Render this Doc."""
        return self.Article.Doc.Root.Render(DisplayEditable = DisplayEditable)
    
    def RenderEditForm(self, ID):
        """Render edit form of node
        
        @param ID: ID of node to render edit form 
        """
        return self.Article.Doc[ID].RenderForm()
    
    def RerenderNode(self, ID):
        """Rerender a node
        
        @param ID: Target node's id 
        """
        return self.Article.Doc[ID].RenderContent(DisplayEditable = True)
    
    @Template(source = InsertForm)
    def RenderInsertForm(self, ID, PushBack):
        """Render insert form
        
        @param ID: ID of node to render
        @param Push_back: Push back or insert front  
        """
        return dict(ID = ID, ModuleList = WidgetManager.ModuleList, PushBack = PushBack)
    
    def RenderHeader(self, DisplayEditable = False):
        """Render header of article
        
        @param DisplayEditable: Display editable or not 
        @retun Header of this article
        """
        Header = []
        for ModuleName in WidgetManager.ModuleList:
            Module = WidgetManager.ModuleList[ModuleName]
            for WidgetName in Module.WidgetList:
                Widget = getattr(Module, WidgetName)
                Header.append(Widget.RenderHeader(DisplayEditable))
        return Header